import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart'; // 添加foundation库导入，用于listEquals
import 'package:flutter_base/base/widget/base_get_builder.dart';
import 'package:flutter_base/config/app_color.dart';
import 'package:flutter_base/generated/assets.dart';
import 'package:flutter_base/pages/test_detail/model/model_test_detail.dart';
import 'package:flutter_base/pages/test_questions/test_questions_logic.dart';
import 'package:flutter_base/pages/test_questions/widgets/choice_question_widget.dart';
import 'package:flutter_base/pages/test_questions/widgets/circle_options_widget.dart';
import 'package:flutter_base/pages/test_questions/widgets/color_psychology_widget.dart';
import 'package:flutter_base/pages/test_questions/widgets/image_choice_question_widget.dart';
import 'package:flutter_base/pages/test_questions/widgets/percentage_allocation_widget.dart';
import 'package:flutter_base/pages/test_questions/widgets/picture_and_text_widget.dart';
import 'package:flutter_base/pages/test_questions/widgets/picture_flip_widget.dart';
import 'package:flutter_base/pages/test_questions/widgets/ranking_question_widget.dart';
import 'package:flutter_base/pages/test_questions/widgets/swipe_scale_widget.dart';
import 'package:flutter_base/utils/log/utils_log.dart';
import 'package:flutter_base/widgets/appbar/common_app_bar.dart';
import 'package:flutter_base/widgets/button/common_button.dart';
import 'package:flutter_base/widgets/image/auto_image.dart';
import 'package:flutter_base/widgets/widget_line.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'dart:ui';
import 'dart:async';
import 'dart:math'; // 添加数学库导入

// 使用项目中已有的SizeExtension扩展方法

class TestQuestionsPage extends StatelessWidget {
  final logic = Get.put(TestQuestionsLogic());

  TestQuestionsPage({super.key});

  @override
  Widget build(BuildContext context) {
    return PopScope(
        canPop: false,
        child: BaseGetBuilder<TestQuestionsLogic>(
          backgroundColor: AppColor.primary,
          builder: (controller) {
            return Column(
              children: [
                SizedBox(
                  height: 24.w + ScreenUtil().statusBarHeight,
                ),
                Container(
                  margin: EdgeInsets.symmetric(horizontal: 27.w),
                  height: 12.w,
                  decoration: BoxDecoration(
                      color: AppColor.colorWhite60,
                      borderRadius: BorderRadius.only(
                          topRight: Radius.circular(12.w),
                          topLeft: Radius.circular(12.w))),
                ),
                _buildQuestionCard(),
              ],
            );
          },
        ));
  }

  Widget _buildQuestionCard() {
    return Expanded(
      child: Container(
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.only(
            topRight: Radius.circular(24.w),
            topLeft: Radius.circular(24.w),
          ),
        ),
        child: Column(
          children: [
            _buildQuestionTitle(),
            const WidgetLine(),
            24.verticalSpaceFromWidth,
            Obx(() {
              return _buildNumberIndicator();
            }),
            16.verticalSpaceFromWidth,
            Obx(() {
              return _buildProgressIndicator();
            }),
            32.verticalSpaceFromWidth,
            // Divider(height: 1.w, color: AppColor.colorF5F5F5),
            _buildQuestionContent(),
            44.verticalSpaceFromWidth,
            Expanded(
              child: Obx(() {
                return _buildAnswerOptions();
              }),
            ),
            // const Spacer(),

            SizedBox(height: 8.w),

            Padding(
              padding: EdgeInsets.symmetric(horizontal: 24.w),
              child: Obx(() {
                // 判断当前问题是否已选择答案
                final currentQuestionId = logic.currentQuestion?.id ?? 0;
                // final questionType = logic.currentQuestion?.type ?? 1;

                bool hasAnswer =
                    logic.userAnswers[currentQuestionId]?.isNotEmpty == true;
                if (logic.currentQuestion?.type == 7) {
                  hasAnswer = logic.userAnswers[logic.currentQuestion?.id ?? 0]
                          ?.fold(0, (sum, item) => sum + item) ==
                      100;
                }
                // // if (logic.userAnswers[currentQuestionId].isNotEmpty)
                //
                // if (currentQuestionId != null) {
                //   if (questionType == 1) {
                //     // 单选题 - 只需检查是否有答案
                //     hasAnswer =
                //         logic.userAnswers.containsKey(currentQuestionId);
                //   } else if (questionType == 2) {
                //     // 多选题 - 检查答案列表是否非空
                //     final answers = logic.userAnswers[currentQuestionId];
                //     hasAnswer = answers != null &&
                //         (answers is List && answers.isNotEmpty);
                //   } else if (questionType == 3) {
                //     // 滑动打分题 - 只要用户设置过值，就视为已回答
                //     hasAnswer =
                //         logic.userAnswers.containsKey(currentQuestionId);
                //   } else if (questionType == 4) {
                //     // 排序题 - 选项排序后即可视为已回答
                //     // hasAnswer = logic.rankingOptions.isNotEmpty;
                //   }
                // }

                return CommonButton.expend(
                  title: logic.isLastQuestion ? '完成' : '下一题',
                  onClick: () => logic.nextQuestion(),
                  type: hasAnswer ? ButtonType.primary : ButtonType.disabled,
                );
              }),
            ),
            SizedBox(height: 8.w + ScreenUtil().bottomBarHeight),
          ],
        ),
      ),
    );
  }

  Widget _buildNumberIndicator() {
    final currentIndex = logic.currentQuestionIndex.value + 1;
    final total = logic.totalQuestions;

    // 格式化为两位数
    String currentStr = currentIndex.toString().padLeft(2, '0');
    String totalStr = total.toString().padLeft(2, '0');

    return Container(
      width: double.infinity,
      height: 44.w,
      padding: EdgeInsets.symmetric(horizontal: 16.w),
      // padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 10.w),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          logic.isFirstQuestion == false
              ? GestureDetector(
                  onTap: () => logic.previousQuestion(),
                  child: SizedBox(
                    width: 40.w,
                    height: 40.w,
                    child: Center(
                      child: AutoImage(
                        Assets.testQuestionsLeft,
                        width: 24.w,
                      ),
                    ),
                  ),
                )
              : 40.horizontalSpace,
          Expanded(
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text(
                  currentStr,
                  style: TextStyle(
                    fontSize: 18.sp,
                    fontWeight: FontWeight.w700,
                    color: AppColor.color0C0A09,
                  ),
                ),
                Text(
                  ' / ',
                  style: TextStyle(
                    fontSize: 18.sp,
                    fontWeight: FontWeight.w700,
                    color: AppColor.color0C0A09.withOpacity(0.16),
                  ),
                ),
                Text(
                  totalStr,
                  style: TextStyle(
                    fontSize: 18.sp,
                    fontWeight: FontWeight.w700,
                    color: AppColor.color0C0A09.withOpacity(0.16),
                  ),
                ),
              ],
            ),
          ),
          logic.isLastQuestion == false
              ? GestureDetector(
                  onTap: () => logic.nextQuestion(),
                  child: SizedBox(
                    width: 40.w,
                    height: 40.w,
                    child: Center(
                      child: AutoImage(
                        Assets.testQuestionsRight,
                        width: 24.w,
                      ),
                    ),
                  ),
                )
              : 40.horizontalSpace,
        ],
      ),
    );
  }

  Widget _buildQuestionTitle() {
    return SizedBox(
      height: 72.w,
      child: Row(
        children: [
          16.horizontalSpace,
          40.horizontalSpace,
          // 标题（中间）
          Expanded(
            child: Text(
              logic.testDetail.name ?? "Myers-Briggs Type Indicator",
              style: TextStyle(
                fontSize: 16.sp,
                fontWeight: FontWeight.w500,
                color: AppColor.primary,
                letterSpacing: 0,
                height: 1.26,
              ),
              textAlign: TextAlign.center,
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
            ),
          ),

          // 关闭按钮（右侧）
          GestureDetector(
            onTap: () => Get.back(),
            child: SizedBox(
              width: 40.w,
              height: 40.w,
              child: Center(
                  child: AutoImage(
                Assets.iconTestClose,
                width: 24.w,
              )),
            ),
          ),
          SizedBox(width: 16.w),
        ],
      ),
    );
  }

  Widget _buildQuestionContent() {
    return Padding(
        padding: EdgeInsets.symmetric(
          horizontal: 24.w,
        ),
        child: Obx(() {
          return Text(
            logic.currentQuestion?.content ?? '',
            style: TextStyle(
              fontSize: 18.sp,
              fontWeight: FontWeight.w600,
              color: AppColor.color0C0A09,
              height: 1.26, // 行高约为22.68px
            ),
          );
        }));
  }

  Widget _buildAnswerOptions() {
    final questionType = logic.currentQuestion?.type ?? 1; // 默认为单选题
// logic.questions.last.type = 9;

    if (questionType == 1) {
      return Padding(
          padding: EdgeInsets.symmetric(horizontal: 24.w),
          child: ChoiceQuestionWidget(logic: logic));
    } else if (questionType == 2) {
      return Padding(
          padding: EdgeInsets.symmetric(horizontal: 24.w),
          child: ChoiceQuestionWidget(logic: logic));
    } else if (questionType == 3) {
      return SwipeScaleWidget(logic: logic);
    } else if (questionType == 6) {
      return CircleOptionsWidget(logic: logic);
    } else if (questionType == 4) {
      return Padding(
        padding: EdgeInsets.symmetric(horizontal: 24.w),
        child: RankingQuestionWidget(
          logic: logic,
        ),
      );
    } else if (questionType == 5) {
      return Padding(
        padding: EdgeInsets.symmetric(horizontal: 24.w),
        child: ImageChoiceQuestionWidget(logic: logic),
      );
    } else if (questionType == 7) {
      return Padding(
        padding: EdgeInsets.symmetric(horizontal: 24.w),
        child: PercentageAllocationWidget(logic: logic),
      );
    } else if (questionType == 8) {
      return ColorPsychologyWidget(logic: logic);
    } else if (questionType == 9) {
      return PictureFlipWidget(logic: logic);
    } else if (questionType == 10) {
      return PictureAndTextWidget(logic: logic);
    }

    return Container();
  }

  // 情绪选择器
  // Widget _buildCircleOptionsWidget() {
  //   // 获取当前问题ID
  //   final questionId = logic.currentQuestion?.id ?? 0;
  //
  //   // 确保已初始化选项
  //   if (logic.currentQuestion != null &&
  //       !logic.selectedOptionIds.containsKey(questionId)) {
  //     // logic.initSelectedOptions();
  //   }
  //
  //   return CircleOptionsWidget(
  //     options: logic.currentQuestion?.options ?? [],
  //     selectedIds: logic.selectedOptionIds[questionId] ?? [],
  //     onSelectionChanged: (selectedOptionIds) {
  //       if (logic.currentQuestion != null) {
  //         int questionId = logic.currentQuestion!.id!;
  //         logic.userAnswers[questionId] = selectedOptionIds;
  //         logic.selectedOptionIds[questionId] = selectedOptionIds;
  //       }
  //     },
  //   );
  // }

  Widget _buildProgressIndicator() {
    return Container(
      height: 6.w,
      margin: EdgeInsets.symmetric(horizontal: 20.w),
      child: Row(
        children: List.generate(logic.totalQuestions, (index) {
          // 是否是已完成的问题
          bool isCompleted = index <= logic.currentQuestionIndex.value;
          return Expanded(
            child: Container(
              margin: EdgeInsets.symmetric(horizontal: 4.w),
              decoration: BoxDecoration(
                color: isCompleted
                    ? AppColor.primary
                    : AppColor.primary.withOpacity(0.23),
                // borderRadius: BorderRadius.circular(3.w),
              ),
            ),
          );
        }),
      ),
    );
  }
}
